package com.megalith.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelXorHtmlUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.megalith.entities.User;
import com.megalith.utils.MyUtil;
import lombok.SneakyThrows;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description TODO
 * @Author lfp
 * @Date 2021/6/23 18:05
 * @Version 1.0
 */
@RestController
@RequestMapping("poi")
public class EasyPoiController {


    /**
    *@Description 直接下载到目录
    *@param
    *@Return
    */
    @SneakyThrows
    @GetMapping("dowload")
    public void doloadExcel(){
        //准备数据集合  可以service接口获取
        List<User> mockData = MyUtil.getMockData();

        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("计算机一班学生","学生"),
                User.class, mockData);


        FileOutputStream fos = new FileOutputStream("D:/user.xls");
        workbook.write(fos);
        fos.close();
    }

    /**
     *@Description 文件流方式返回
     *@param
     *@Return
     */
    @GetMapping("export")
    public void exportExcel(HttpServletResponse response) throws IOException {
        List<User> mockData = MyUtil.getMockData();

        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("学生表","学生"),
                User.class, mockData);

        ServletOutputStream outputStream = response.getOutputStream();
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/force-download");
        response.setHeader("Content-Disposition","attachment;filename=student.xlsx");
        //response.setContentType("application/octet-stream;charset=UTF-8");

        workbook.write(outputStream);
        workbook.close();
    }

    /**
     *@Description 在线预览
     *@param
     *@Return
     */
    @GetMapping("review")
    public void reviewExcel(HttpServletResponse response) throws IOException {
        List<User> mockData = MyUtil.getMockData();

        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("学生表","学生"),
                User.class, mockData);

        response.getOutputStream().write(ExcelXorHtmlUtil.toAllHtml(workbook).getBytes());

    }
}
